<template>
  <div class="home-container">
    <!-- 头部导航组件 -->
    <HeaderComponent />
    <!-- 错误状态 -->
    <div v-if="error" class="error-container">
      <el-alert
        title="加载失败"
        :description="error"
        type="error"
        show-icon
        :closable="false"
      />
      <el-button type="primary" @click="retryLoad" style="margin-top: 20px;">
        重试
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-container">
      <el-icon class="loading-icon" :size="40">
        <Loading />
      </el-icon>
      <p>正在加载...</p>
    </div>

    <!-- 主要内容 -->
    <div v-else>
      <el-card class="home-card">
        <template #header>
          <div class="card-header">
            <h2>欢迎回来</h2>
            <el-button type="danger" @click="handleLogout">退出登录</el-button>
          </div>
        </template>

        <div class="user-info">
          <el-descriptions title="用户信息" :column="1" border>
            <el-descriptions-item label="用户ID">
              {{ userInfo.user_id || '未获取' }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号">
              {{ userInfo.phone || '未获取' }}
            </el-descriptions-item>
            <el-descriptions-item label="用户名">
              {{ userInfo.username || '未获取' }}
            </el-descriptions-item>
            <el-descriptions-item label="实名认证状态">
              <el-tag :type="verifyStatus === '1' ? 'success' : 'warning'">
                {{ verifyStatus === '1' ? '已认证' : '未认证' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="actions">
          <el-button type="primary" @click="getUserInfo" :loading="refreshing">刷新用户信息</el-button>
          <el-button @click="showToken">查看Token</el-button>
          <el-button
            v-if="verifyStatus !== '1'"
            type="success"
            @click="goToIdCardVerification"
          >
            身份证实名认证
          </el-button>

        </div>
      </el-card>

      <!-- 顶部欢迎区域 -->
      <div class="welcome-section">
        <div class="welcome-content">
          <div class="welcome-text">
            <h1 class="welcome-title">欢迎回来，{{ userInfo.username || '用户' }}！</h1>
            <p class="welcome-subtitle">今天也要保持健康的生活方式哦</p>
            <div class="welcome-stats">
              <div class="stat-item">
                <div class="stat-number">{{ todayDate }}</div>
                <div class="stat-label">今日日期</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ currentTime }}</div>
                <div class="stat-label">当前时间</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ weatherInfo.icon }} {{ weatherInfo.temperature }}</div>
                <div class="stat-label">{{ weatherInfo.condition }}</div>
              </div>
            </div>
          </div>
          <div class="welcome-actions">
            <el-button type="primary" size="large" @click="goToProfile" class="primary-action">
              <el-icon><User /></el-icon>
              开始健康饮食之旅
            </el-button>
            <el-button size="large" @click="handleLogout" class="logout-btn">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-button>
          </div>
        </div>
      </div>

      <!-- 用户信息卡片 -->
      <div class="user-info-section">
        <el-card class="user-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#409eff"><User /></el-icon>
              <span>用户信息</span>
              <el-button type="text" @click="getUserInfo" :loading="refreshing">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>

          <div class="user-details">
            <div class="user-avatar">
              <el-avatar :size="80" :src="userInfo.avatar">
                {{ userInfo.username?.charAt(0)?.toUpperCase() || 'U' }}
              </el-avatar>
            </div>
            <div class="user-data">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="用户ID">
                  <el-tag size="small" type="info">{{ userInfo.user_id || '未设置' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="用户名">
                  <span class="username">{{ userInfo.username || '未设置' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="手机号">
                  <span class="phone">{{ userInfo.phone || '未设置' }}</span>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>

          <div class="user-actions">
            <el-button type="text" @click="showToken">
              <el-icon><Key /></el-icon>
              查看Token
            </el-button>
            <el-button type="text" @click="goToProfile">
              <el-icon><Setting /></el-icon>
              个人设置
            </el-button>
            <el-button type="text" @click="showUserGuide">
              <el-icon><QuestionFilled /></el-icon>
              使用指南
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 功能导航区域 -->
      <div class="features-section">
        <div class="section-header">
          <h2>功能导航</h2>
          <p>选择您需要的功能模块</p>
        </div>

        <!-- 健康饮食推荐功能 -->
        <div class="main-features">
          <h3 class="feature-category">健康饮食推荐</h3>
          <el-row :gutter="24">
            <el-col :xs="24" :sm="12" :md="6">
              <el-card class="feature-card primary" shadow="hover" @click="goToProfile">
                <div class="feature-content">
                  <div class="feature-icon">
                    <el-icon size="48" color="#409eff"><User /></el-icon>
                  </div>
                  <h4>个人信息收集</h4>
                  <p>完善您的身体指标、健身目标和偏好设置，为个性化推荐做准备</p>
                  <div class="feature-badge">基础</div>
                </div>
              </el-card>
            </el-col>

            <el-col :xs="24" :sm="12" :md="6">
              <el-card class="feature-card" shadow="hover" @click="goToDietPlan">
                <div class="feature-content">
                  <div class="feature-icon">
                    <el-icon size="48" color="#67c23a"><Food /></el-icon>
                  </div>
                  <h4>生成饮食计划</h4>
                  <p>基于您的身体指标和健身目标，生成个性化的饮食计划</p>
                </div>
              </el-card>
            </el-col>

            <el-col :xs="24" :sm="12" :md="6">
              <el-card class="feature-card" shadow="hover" @click="goToHistory">
                <div class="feature-content">
                  <div class="feature-icon">
                    <el-icon size="48" color="#e6a23c"><Clock /></el-icon>
                  </div>
                  <h4>历史计划</h4>
                  <p>查看和管理您之前生成的饮食计划记录</p>
                </div>
              </el-card>
            </el-col>

            <el-col :xs="24" :sm="12" :md="6">
              <el-card class="feature-card" shadow="hover" @click="goToNutritionAnalysis">
                <div class="feature-content">
                  <div class="feature-icon">
                    <el-icon size="48" color="#f56c6c"><DataBoard /></el-icon>
                  </div>
                  <h4>食品营养分析</h4>
                  <p>扫描食品包装，智能分析营养成分，提供个性化建议</p>
                  <div class="feature-badge">AI</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>




    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  SwitchButton, 
  Refresh, 
  Key, 
  Setting, 
  QuestionFilled, 
  Loading,
  Food,
  Clock,
  DataBoard
} from '@element-plus/icons-vue'
import { authAPI } from '@/api/index'
import HeaderComponent from '@/components/header.vue'

const router = useRouter()

// 用户信息
const userInfo = ref({
  user_id: '',
  phone: '',
  username: '',
  avatar: ''
})

// 认证状态
const verifyStatus = ref('0')

// 刷新状态
const refreshing = ref(false)

// 加载状态
const loading = ref(true)

// 错误状态
const error = ref(null)

// 今日日期
const todayDate = ref('')

// 当前时间
const currentTime = ref('')

// 天气信息
const weatherInfo = ref({
  icon: '☀️',
  temperature: '25°C',
  condition: '晴天'
})

// 时间更新定时器
let timeInterval = null

// 获取用户信息
const getUserInfo = async () => {
  try {
    refreshing.value = true
    error.value = null
    const response = await authAPI.getUserInfo()
    if (response.success) {
      userInfo.value = response.data
      // 更新localStorage中的用户信息
      localStorage.setItem('userInfo', JSON.stringify(response.data))
      ElMessage.success('用户信息获取成功')
    } else {
      throw new Error(response.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    error.value = error.message || '获取用户信息失败，请检查网络连接'
    ElMessage.error(error.value)
  } finally {
    refreshing.value = false
    loading.value = false
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await authAPI.logout()
    if (response.success) {
      // 清除localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')

      ElMessage.success('退出登录成功')
      router.push('/login')
    } else {
      ElMessage.error(response.message || '退出登录失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出登录失败:', error)
    }
  }
}

// 显示Token
const showToken = () => {
  const token = localStorage.getItem('token')
  if (token) {
    ElMessageBox.alert(token, '当前Token', {
      confirmButtonText: '确定',
      type: 'info'
    })
  } else {
    ElMessage.warning('未找到Token')
  }
}

// 获取认证状态
const getVerifyStatus = async () => {
  try {
    const response = await authAPI.getIdCardStatus()
    console.log('获取认证状态响应:', response) // 调试信息
    if (response && response.data && response.data.success) {
      verifyStatus.value = response.data.data.verify_status
      console.log('更新认证状态为:', verifyStatus.value) // 调试信息
    }
  } catch (error) {
    console.error('获取认证状态失败:', error)
  }
}

// 跳转到个人资料页面
const goToProfile = () => {
  router.push('/user-profile')
}

// 跳转到身份证认证页面
const goToIdCardVerification = () => {
  router.push('/id-card-verification')
}

// 显示使用指南
const showUserGuide = () => {
  ElMessage.info('使用指南功能正在开发中...')
}

// 跳转到饮食计划页面
const goToDietPlan = () => {
  router.push('/diet-plan')
}

// 跳转到历史记录页面
const goToHistory = () => {
  router.push('/historical-diet-plan')
}

// 跳转到营养分析页面
const goToNutritionAnalysis = () => {
  router.push('/nutrition-analysis')
}

// 重试加载
const retryLoad = async () => {
  loading.value = true
  error.value = null
  try {
    await getUserInfo()
  } catch (error) {
    console.error('重试加载失败:', error)
  }
}

// 更新当前时间
const updateCurrentTime = () => {
  const now = new Date()
  todayDate.value = now.toLocaleDateString('zh-CN')
  currentTime.value = now.toLocaleTimeString('zh-CN')
}

// 模拟获取天气信息
const getWeatherInfo = () => {
  // 这里可以接入真实的天气API
  const weatherOptions = [
    { icon: '☀️', temperature: '25°C', condition: '晴天' },
    { icon: '⛅', temperature: '22°C', condition: '多云' },
    { icon: '🌧️', temperature: '18°C', condition: '小雨' },
    { icon: '❄️', temperature: '5°C', condition: '小雪' }
  ]
  const randomWeather = weatherOptions[Math.floor(Math.random() * weatherOptions.length)]
  weatherInfo.value = randomWeather
}

// 组件挂载时初始化
onMounted(async () => {
  try {
    // 从localStorage获取用户信息
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      try {
        userInfo.value = JSON.parse(storedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
      }
    } else {
      // 如果没有本地存储的用户信息，则从服务器获取
      await getUserInfo()
    }

    // 初始化时间和天气信息
    updateCurrentTime()
    getWeatherInfo()
    getVerifyStatus()

    // 启动时间更新定时器
    timeInterval = setInterval(updateCurrentTime, 1000)
  } catch (error) {
    console.error('初始化失败:', error)
    error.value = '无法加载用户信息，请稍后再试。'
  } finally {
    loading.value = false
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  color: white;
  font-size: 18px;
}

.loading-container p {
  margin-top: 20px;
  font-weight: 500;
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  color: white;
  font-size: 18px;
  padding: 20px;
}

.error-container .el-alert {
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
}

.error-container .el-alert__title {
  color: white;
}

.error-container .el-alert__description {
  color: rgba(255, 255, 255, 0.8);
}

.home-card {
  width: 100%;
  max-width: 600px;
  margin: 0 auto 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #333;
}

.user-info {
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
}

/* 欢迎区域样式 */
.welcome-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  padding: 30px;
  margin-bottom: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.welcome-text {
  flex: 1;
  min-width: 300px;
}

.welcome-title {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
  font-weight: 700;
}

.welcome-subtitle {
  font-size: 1.1rem;
  color: #666;
  margin-bottom: 20px;
}

.welcome-stats {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 10px;
  color: white;
  min-width: 120px;
}

.stat-number {
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.9;
}

.welcome-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

/* 用户信息卡片样式 */
.user-info-section {
  margin-bottom: 20px;
}

.user-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.user-details {
  display: flex;
  gap: 20px;
  align-items: center;
  margin-bottom: 20px;
}

.user-avatar {
  flex-shrink: 0;
}

.user-data {
  flex: 1;
}

.username {
  font-weight: bold;
  color: #409eff;
}

.phone {
  color: #666;
}

.user-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

/* 功能导航样式 */
.features-section {
  margin-bottom: 20px;
}

.section-header {
  text-align: center;
  margin-bottom: 30px;
  color: white;
}

.section-header h2 {
  font-size: 2rem;
  margin-bottom: 10px;
  font-weight: 700;
}

.section-header p {
  font-size: 1.1rem;
  opacity: 0.9;
}

.feature-category {
  color: white;
  font-size: 1.5rem;
  margin-bottom: 20px;
  font-weight: 600;
}

.feature-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 100%;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.2);
}

.feature-content {
  text-align: center;
  padding: 20px;
}

.feature-icon {
  margin-bottom: 15px;
}

.feature-content h4 {
  font-size: 1.2rem;
  margin-bottom: 10px;
  color: #333;
}

.feature-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.feature-badge {
  display: inline-block;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 5px 15px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: bold;
}



/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  gap: 20px;
}

.loading-icon {
  color: #409eff;
  animation: spin 2s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}



/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
    text-align: center;
  }

  .welcome-title {
    font-size: 2rem;
  }

  .welcome-stats {
    justify-content: center;
  }

  .user-details {
    flex-direction: column;
    text-align: center;
  }

  .card-header {
    flex-direction: column;
    gap: 10px;
  }

  .actions {
    flex-direction: column;
  }

  .welcome-actions {
    justify-content: center;
  }

  .user-actions {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .home-container {
    padding: 10px;
  }

  .welcome-section {
    padding: 20px;
  }

  .welcome-title {
    font-size: 1.8rem;
  }

  .stat-item {
    min-width: 100px;
    padding: 10px;
  }

  .stat-number {
    font-size: 1.2rem;
  }
}
</style>
